
const {EnterpriseModel, AdminUserModel, RoleModel} = require('../../models/index')
const koaTool = require('../../commons/koa_tool')
const { setZero } = require("../../commons/util")  
const passwordUtility = require('../../commons/password_utility')
const _const = require('../../commons/const')
const mqttService = require("../../services/mqtt")
class EnterpriseController {

    //新增
    create = async (ctx) => {

        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        let {
            name,         //企业名称
            code,         //组织代码
            address,      //地址
            principal,    //负责人
            concat_phone, //联系电话
            industry,     //行业类别
            scale,        //规模
            capital,      //实交资本（万元）
            legal_person, //法人
        } = input;

        const {isNull} = require("../../commons/util.js");


        let validKeys = [
            {prop: "name", label: "企业名称"},
            {prop: "code", label: "组织代码"},
            {prop: "address", label: "公司地址"},
            {prop: "principal", label: "负责人"},
            {prop: "concat_phone", label: "联系电话"},
            {prop: "industry", label: "行业类别"},
            {prop: "scale", label: "规模"},
        ];

        let unValidIdx = validKeys.findIndex(item => {
            return isNull(item.prop)
        });
        if(unValidIdx != -1){
            return koaTool.error(ctx,`${validKeys[unValidIdx].label}不能为空`);
        }

        // 获取角色为 “公司账号id”
        let roleData = await RoleModel.findOne({name: "公司账号"});
        if(!roleData){
            return koaTool.error(ctx,"请先创建角色为“公司账号”的数据"); 
        }


        let newData = Object.assign({}, input, {
            status: 1
        })

        let enterpriseData = await EnterpriseModel.create(newData)
        if(enterpriseData.topic){
            mqttService.enterpriseTopicData.set(enterpriseData._id.toString(), enterpriseData.topic)
        }

        //  创建账号 企业对应账号格式PNT22022001
        let now = new Date();
        let enterCode = `SSD${now.getFullYear().toString().slice(-2)}${setZero(now.getMonth() + 1)}${setZero(now.getDate())}`
        let adminUserData = await AdminUserModel.find({'username': {$regex: enterCode}});
        if(adminUserData.length > 0){
            let adminUserItem = adminUserData[adminUserData.length - 1];
            let codeNum = parseInt(adminUserItem.username.slice(11)) + 1;
            enterCode += ("00" + codeNum).slice(-3);
        }else{
            enterCode += "001";
        };
        let enterAdminUser = {
            username: enterCode,
            password: passwordUtility.cookPw(123456),
            role_type: _const.ADMIN_USER_ROLE.ROOT_WAREHOUSE_USER,
            is_super: 1,
            role: roleData._id,
            name: input.name,
            enterprise_id: enterpriseData._id,
        }
        let enterAdminUserRes = await AdminUserModel.create(enterAdminUser);
        mqttService.initMsgConfigData("enterprise")
        return koaTool.success(ctx,'创建成功');
    }

    //详情
    detail = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        const detail = await EnterpriseModel.findById(input.id)
        if(detail){
            return koaTool.success(ctx,'获取成功',{
                detail
            });
        }
        return koaTool.error(ctx,'无该类目信息');
    }
    //更新
    update = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        let detail = await EnterpriseModel.findById(input.id)
        if (!detail) {
            return koaTool.error(ctx,"类目异常");
        }
        const {
            name,         //企业名称
            code,         //组织代码
            address,      //地址
            principal,    //负责人
            concat_phone, //联系电话
            industry,     //行业类别
            scale,        //规模
            capital,      //实交资本（万元）
            legal_person, //法人
            send_msg_status, // 发送短信状态
            lng_lat,
        } = input;

        let fields = ['name', 'code', 'address', 'principal', 'concat_phone', 'industry', 'scale', 'capital','legal_person', 'topic']

        fields.forEach(field => {
            if(input[field]){
                detail[field] = input[field]
            }
        })

        detail.send_msg_status = send_msg_status || false;

        if(lng_lat && lng_lat.length){
            detail.lng_lat = lng_lat;
        }

        await detail.save()
        mqttService.initMsgConfigData("enterprise")
        if(detail.topic){
            mqttService.enterpriseTopicData.set(detail._id.toString(), detail.topic)
        }
        return koaTool.success(ctx, '编辑成功');
    }
    //删除
    delete = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        let detail = await EnterpriseModel.findById(input.id)
        if (!detail) {
            return koaTool.error(ctx,"类目异常");
        }

        detail.status = 2;  //标记删除

        await detail.save();
        mqttService.initMsgConfigData("enterprise")
        // 对应删除登录账号
        let adminUser =  await AdminUserModel.findOne({enterprise_id: input.id});
        adminUser.status = 2;
        adminUser.disable = true;
        await adminUser.save();
        
        return koaTool.success(ctx, '删除成功');
    }
    //列表
    list = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['page'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        let {
            page,
            limit,
            search,
            industry,
        } = ctx.request.query;

        const {isNull} = require('../../commons/util.js');



        limit = Number(limit)
        page = page || 0
        page = page - 1
        let query = {
            status: 1,
        };

        if(!isNull(industry)){
            query['industry'] = industry;
        }

        if (search) {
            const reg = new RegExp(search, 'i') //不区分大小写
            query.$and = query.$and || []
            query.$and.push({
                $or: [
                    {'name': {$regex: reg}},
                ]
            })
        }

        let total = await EnterpriseModel.countDocuments(query)
        let list = await EnterpriseModel.find(query).sort([
            ['create_at',-1],
        ]).skip(page * limit).limit(limit).lean();
        const {SEND_MSG_STATUS} = require('../../commons/const.js');

        list.forEach(item => {
            item.sendMsgStatusName = SEND_MSG_STATUS[item.send_msg_status]
        })

        koaTool.succ(ctx, {
            list,
            total
        })
    }

    // 获取企业字典
    getDictByEnterprise = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, []);
        
        let params = {
            status: 1,
        }
        
        if(ctx.state._user.enterprise_id){
            params._id = ctx.state._user.enterprise_id;
        }

        let dataList = await EnterpriseModel.find(params);
        let resDataList = dataList.map(item => {
            return {
                dictValue: item._id,
                dictLabel: item.name
            }
        })
        return koaTool.success(ctx,"获取成功",resDataList)
    }


    getEnterpriseScaleMap = async (ctx) => {

        const {ENTERPRISE_SCALE_MAP} = require('../../commons/const.js');

        return koaTool.success(ctx,"获取成功",{
            map: ENTERPRISE_SCALE_MAP
        })
    }

    getEnterpriseScaleList = async (ctx) => {

        const {ENTERPRISE_SCALE_LIST} = require('../../commons/const.js');

        return koaTool.success(ctx,"获取成功",{
            list: ENTERPRISE_SCALE_LIST
        })
    }

    getEnterpriseIndustryMap = async (ctx) => {

        const {ENTERPRISE_INDUSTRY_MAP} = require('../../commons/const.js');

        return koaTool.success(ctx,"获取成功",{
            map: ENTERPRISE_INDUSTRY_MAP
        })
    }

    getEnterpriseIndustryList = async (ctx) => {

        const {ENTERPRISE_INDUSTRY_LIST} = require('../../commons/const.js');

        return koaTool.success(ctx,"获取成功",{
            list: ENTERPRISE_INDUSTRY_LIST
        })
    }

    getDict2SendMsgStatus = async (ctx) => {
        const {SEND_MSG_STATUS_LIST} = require('../../commons/const.js');

        return koaTool.success(ctx,"获取成功",{
            list: SEND_MSG_STATUS_LIST
        })
    }


}

module.exports=new EnterpriseController()

